import { _decorator, Component, Node } from 'cc'
const { ccclass, property, executeInEditMode } = _decorator

@ccclass('BgMove')
// @executeInEditMode(true)
export class BgMove extends Component {
  @property(Node)
  bg01: Node = null

  @property(Node)
  bg02: Node = null
  
  private bgSpeed = 10 // 每次移动的距离
  private bgMovingRange = 100 // 移动范围

  start(){
    this.init()
  }

  update(deltaTime: number) {
    this.bgMove(deltaTime)
  }

  private bgMove(deltaTime: number) {
    // 移动前 Z 位置
    let startBg1z = this.bg01.position.z
    let startBg2z = this.bg02.position.z
    // 移动后 Z 位置
    let endBg1z = startBg1z + this.bgSpeed * deltaTime
    let endBg2z = startBg2z + this.bgSpeed * deltaTime
    this.bg01.setPosition(0, 0, endBg1z)
    this.bg02.setPosition(0, 0, endBg2z)

    if (endBg1z > this.bgMovingRange) {
      this.bg01.setPosition(0, 0, endBg2z - this.bgMovingRange)
    } else if (endBg2z > this.bgMovingRange) {
      this.bg02.setPosition(0, 0, endBg1z - this.bgMovingRange) 
    }
  }
  private init() {
    this.bg01.setPosition(0, 0, 0)
    this.bg02.setPosition(0, 0, -this.bgMovingRange)
  }
}
